'use client'

import { useState, useEffect, useMemo } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { LayersIcon, FolderIcon, CpuIcon } from 'lucide-react'

// 专业定义
const SPECIALTIES = [
  { code: 'piping', name: '配管专业', description: '管道、阀门、容器等设备' },
  { code: 'electrical', name: '电气专业', description: '电力、照明、配电等设备' },
  { code: 'hvac', name: '暖通专业', description: '通风、空调、供暖等设备' },
  { code: 'communication', name: '通信专业', description: '通信、网络、监控等设备' },
  { code: 'instrumentation', name: '仪表专业', description: '测量、控制、检测等设备' }
]

interface DeviceTypeMapping {
  device_id: string;
  classification_code: string;
  classification_name: string;
  specialty: string;
  name: string;
}

interface ObjectCategory {
  name: string;
  count: number;
  deviceTypes: DeviceTypeMapping[];
}

interface HierarchicalDeviceSelectorProps {
  selectedSpecialty?: string;
  selectedObjectCategory?: string;
  selectedDeviceType?: string;
  onSpecialtyChange?: (specialty: string) => void;
  onObjectCategoryChange?: (category: string) => void;
  onDeviceTypeChange?: (deviceType: string) => void;
  className?: string;
}

export function HierarchicalDeviceSelector({
  selectedSpecialty,
  selectedObjectCategory,
  selectedDeviceType,
  onSpecialtyChange,
  onObjectCategoryChange,
  onDeviceTypeChange,
  className
}: HierarchicalDeviceSelectorProps) {
  const [deviceTypes, setDeviceTypes] = useState<DeviceTypeMapping[]>([]);
  const [objectCategories, setObjectCategories] = useState<ObjectCategory[]>([]);
  const [loading, setLoading] = useState(false);

  // 加载所有设备类型（使用设备实例数据以保持与专业导航一致）
  const loadDeviceTypes = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/device-hierarchy-by-name');
      const data = await response.json();
      if (data.success) {
        // 将层次结构数据转换为设备类型数组
        const allDevices = data.data.flatMap((hierarchy: any) => 
          hierarchy.devices.map((device: any) => ({
            device_id: device.device_id,
            classification_code: device.classification_code,
            classification_name: device.classification_name,
            specialty: device.specialty,
            name: device.name
          }))
        );
        setDeviceTypes(allDevices);
        // 按专业分组生成对象分类
        generateObjectCategories(allDevices);
      }
    } catch (error) {
      console.error('加载设备类型失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 生成对象分类列表（从设备类型中提取）
  const generateObjectCategories = (allDeviceTypes: DeviceTypeMapping[]) => {
    const categoryMap = new Map<string, DeviceTypeMapping[]>();
    
    allDeviceTypes.forEach(deviceType => {
      if (!categoryMap.has(deviceType.classification_name)) {
        categoryMap.set(deviceType.classification_name, []);
      }
      categoryMap.get(deviceType.classification_name)!.push(deviceType);
    });

    const categories: ObjectCategory[] = Array.from(categoryMap.entries()).map(([name, types]) => ({
      name,
      count: types.length,
      deviceTypes: types
    }));

    setObjectCategories(categories);
  };


  // 处理专业选择
  const handleSpecialtyChange = (specialty: string) => {
    onSpecialtyChange?.(specialty);
    // 清空下级选择
    onObjectCategoryChange?.('');
    onDeviceTypeChange?.('');
  };

  // 处理对象分类选择
  const handleObjectCategoryChange = (category: string) => {
    onObjectCategoryChange?.(category);
    // 清空下级选择
    onDeviceTypeChange?.('');
  };

  // 处理设备分类选择
  const handleDeviceTypeChange = (deviceType: string) => {
    onDeviceTypeChange?.(deviceType);
  };

  useEffect(() => {
    loadDeviceTypes();
  }, []);


  // 使用 useMemo 优化性能，避免不必要的重新计算
  const filteredObjectCategories = useMemo(() => {
    if (!selectedSpecialty || objectCategories.length === 0) return [];
    
    // 将英文代码转换为中文名称进行过滤
    const specialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.name;
    if (!specialtyName) return [];
    
    return objectCategories
      .map(category => {
        const filteredDeviceTypes = category.deviceTypes.filter(dt => dt.specialty === specialtyName);
        return {
          ...category,
          deviceTypes: filteredDeviceTypes,
          count: filteredDeviceTypes.length
        };
      })
      .filter(category => category.count > 0);
  }, [selectedSpecialty, objectCategories]);

  const currentFilteredDeviceTypes = useMemo(() => {
    if (!selectedObjectCategory) return [];
    
    const category = objectCategories.find(cat => cat.name === selectedObjectCategory);
    if (!category) return [];
    
    let types = category.deviceTypes;
    if (selectedSpecialty) {
      // 将英文代码转换为中文名称进行过滤
      const specialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.name;
      if (specialtyName) {
        types = types.filter(dt => dt.specialty === specialtyName);
      }
    }
    
    return types;
  }, [selectedSpecialty, selectedObjectCategory, objectCategories]);

  return (
    <Card className={className}>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <LayersIcon className="w-5 h-5" />
          设备分类选择
        </CardTitle>
        <CardDescription>
          按照专业分类 → 对象分类 → 设备分类的层级结构选择设备模板，最终到设备层用于生成设备实例模板
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 第一级：专业选择 */}
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <LayersIcon className="w-4 h-4 text-blue-600" />
            <Label htmlFor="specialty-select" className="text-sm font-medium">
              1. 选择专业分类
            </Label>
          </div>
          <Select value={selectedSpecialty || ''} onValueChange={handleSpecialtyChange}>
            <SelectTrigger>
              <SelectValue placeholder="请选择工程专业" />
            </SelectTrigger>
            <SelectContent>
              {SPECIALTIES.map(specialty => (
                <SelectItem key={specialty.code} value={specialty.code}>
                  <div className="flex flex-col">
                    <span className="font-medium">{specialty.name}</span>
                    <span className="text-xs text-gray-500">{specialty.description}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          
          {selectedSpecialty && (
            <div className="flex items-center gap-2 text-sm text-green-600">
              <span>已选择:</span>
              <Badge variant="secondary">
                {SPECIALTIES.find(s => s.code === selectedSpecialty)?.name}
              </Badge>
            </div>
          )}
        </div>

        {/* 第二级：对象分类选择 */}
        {selectedSpecialty && (
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <FolderIcon className="w-4 h-4 text-green-600" />
              <Label htmlFor="object-category-select" className="text-sm font-medium">
                2. 选择对象分类 ({filteredObjectCategories.length}个可选)
              </Label>
            </div>
            <Select 
              value={selectedObjectCategory || ''} 
              onValueChange={handleObjectCategoryChange}
              disabled={loading || filteredObjectCategories.length === 0}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择对象分类" />
              </SelectTrigger>
              <SelectContent>
                {filteredObjectCategories.length === 0 ? (
                  <SelectItem value="" disabled>
                    没有可用的对象分类
                  </SelectItem>
                ) : (
                  filteredObjectCategories.map(category => (
                    <SelectItem key={category.name} value={category.name}>
                      <div className="flex items-center justify-between w-full">
                        <span>{category.name}</span>
                        <Badge variant="outline" className="ml-2">
                          {category.count}个
                        </Badge>
                      </div>
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
            
            {selectedObjectCategory && (
              <div className="flex items-center gap-2 text-sm text-green-600">
                <span>已选择:</span>
                <Badge variant="secondary">{selectedObjectCategory}</Badge>
                <span className="text-xs text-gray-500">
                  ({filteredObjectCategories.find(c => c.name === selectedObjectCategory)?.count}个设备分类)
                </span>
              </div>
            )}
          </div>
        )}

        {/* 第三级：设备分类选择 */}
        {selectedObjectCategory && currentFilteredDeviceTypes.length > 0 && (
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <CpuIcon className="w-4 h-4 text-purple-600" />
              <Label htmlFor="device-type-select" className="text-sm font-medium">
                3. 选择设备分类 ({currentFilteredDeviceTypes.length}个)
              </Label>
            </div>
            <Select 
              value={selectedDeviceType || ''} 
              onValueChange={handleDeviceTypeChange}
              disabled={loading}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择具体设备分类" />
              </SelectTrigger>
              <SelectContent>
                {currentFilteredDeviceTypes.map(deviceType => (
                  <SelectItem key={deviceType.device_id} value={deviceType.device_id}>
                    {deviceType.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            
            {selectedDeviceType && (
              <div className="flex items-center gap-2 text-sm text-green-600">
                <span>已选择:</span>
                <Badge variant="secondary">
                  {currentFilteredDeviceTypes.find(dt => dt.device_id === selectedDeviceType)?.name}
                </Badge>
                <span className="text-xs text-gray-500">
                  ({currentFilteredDeviceTypes.find(dt => dt.device_id === selectedDeviceType)?.classification_code})
                </span>
              </div>
            )}
          </div>
        )}

        {/* 选择路径显示 */}
        {selectedSpecialty && (
          <div className="mt-6 p-4 bg-blue-50 rounded-lg">
            <div className="text-sm font-medium text-blue-800 mb-2">选择路径:</div>
            <div className="flex items-center gap-2 text-sm">
              <Badge variant="outline">{SPECIALTIES.find(s => s.code === selectedSpecialty)?.name}</Badge>
              {selectedObjectCategory && (
                <>
                  <span className="text-gray-400">→</span>
                  <Badge variant="outline">{selectedObjectCategory}</Badge>
                </>
              )}
              {selectedDeviceType && (
                <>
                  <span className="text-gray-400">→</span>
                  <Badge variant="outline">
                    {currentFilteredDeviceTypes.find(dt => dt.device_id === selectedDeviceType)?.name}
                  </Badge>
                </>
              )}
            </div>
          </div>
        )}

        {/* 说明信息 */}
        <div className="mt-4 p-3 bg-gray-50 rounded-md text-sm text-gray-600">
          <div className="space-y-1">
            <div>• <strong>专业分类</strong>：按工程专业划分（配管、电气、暖通、通信、仪表）</div>
            <div>• <strong>对象分类</strong>：按设备功能分类（如离心泵、闸阀、配电箱等）</div>
            <div>• <strong>设备分类</strong>：具体的设备类型，对应参数表模板，用于设备实例填写</div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}